// 监听扩展安装
chrome.runtime.onInstalled.addListener(function() {
    // 设置默认配置
    chrome.storage.sync.set({
        targetLanguage: 'zh',
        translationApi: 'libre',
        enableSelection: true
    });
});

// 创建上下文菜单
chrome.runtime.onInstalled.addListener(function() {
    chrome.contextMenus.create({
        id: 'translateSelection',
        title: '翻译选中文本',
        contexts: ['selection']
    });
});

// 处理上下文菜单点击
chrome.contextMenus.onClicked.addListener(function(info, tab) {
    if (info.menuItemId === 'translateSelection') {
        chrome.tabs.sendMessage(tab.id, {
            action: 'translateSelection',
            text: info.selectionText
        });
    }
});

// 监听来自content script的消息
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.action === 'translate') {
        // 这里可以添加不同翻译API的处理逻辑
        handleTranslation(request.text, request.targetLanguage, request.api)
            .then(sendResponse)
            .catch(error => sendResponse({ error: error.message }));
        return true; // 保持消息通道开放
    }
});

// 处理不同的翻译API
async function handleTranslation(text, targetLanguage, api) {
    switch (api) {
        case 'libre':
            return await translateWithLibre(text, targetLanguage);
        case 'google':
            return await translateWithGoogle(text, targetLanguage);
        case 'baidu':
            return await translateWithBaidu(text, targetLanguage);
        default:
            throw new Error('Unsupported translation API');
    }
}

// LibreTranslate API
async function translateWithLibre(text, targetLanguage) {
    const response = await fetch('https://libretranslate.de/translate', {
        method: 'POST',
        body: JSON.stringify({
            q: text,
            source: 'auto',
            target: targetLanguage
        }),
        headers: {
            'Content-Type': 'application/json'
        }
    });

    if (!response.ok) {
        throw new Error('Translation failed');
    }

    const data = await response.json();
    return data.translatedText;
}

// Google Translate API (需要API密钥)
async function translateWithGoogle(text, targetLanguage) {
    // 实现Google翻译API调用
    throw new Error('Google Translate API not implemented');
}

// 百度翻译API (需要API密钥)
async function translateWithBaidu(text, targetLanguage) {
    // 实现百度翻译API调用
    throw new Error('Baidu Translate API not implemented');
}
